using System;
using Cinemachine;
using DG.Tweening; 
using UnityEngine;
using UnityEngine.Serialization;

public class HandleSpotlinghtManager : SingletonMono<HandleSpotlinghtManager>
{
    public Lattice currentSpotlightLattice = null;
    
    public CinemachineVirtualCamera virtualCamera;
    private CinemachineFramingTransposer transposer;
    
    public float duration = 0.1f;
    

    private void OnEnable()
    {
        EventCenter.GetInstance().AddEventListener<Lattice>("SpotlightChanged",SpotlightLatticeChanged);
        EventCenter.GetInstance().AddEventListener("SpotlightClear",ClearSpotlightLattice);

        transposer = virtualCamera.GetCinemachineComponent<CinemachineFramingTransposer>();

        
        transposer.m_SoftZoneHeight = 0;
        transposer.m_SoftZoneWidth = 0;
        virtualCamera.Follow=transform;
        virtualCamera.m_Lens.OrthographicSize = 4.2f;
    }

    private void OnDisable()
    {
        EventCenter.GetInstance().RemoveEventListener<Lattice>("SpotlightChanged",SpotlightLatticeChanged);
        EventCenter.GetInstance().RemoveEventListener("SpotlightClear",ClearSpotlightLattice);
    }

    private void ClearSpotlightLattice()
    {
        if(!currentSpotlightLattice)
            return;
        currentSpotlightLattice = null;
        
        // 使用 DOTween 移动物体到目标位置
        transform.DOMove(Vector3.zero, duration);

        // 使用 DOTween 改变虚拟相机的 OrthographicSize
        DOTween.To(() => virtualCamera.m_Lens.OrthographicSize, 
            x => virtualCamera.m_Lens.OrthographicSize = x, 
            4.2f, 
            duration);
        
        EventCenter.GetInstance().EventTrigger("HideChessUI");
        
    }

    private void SpotlightLatticeChanged(Lattice newLattice)
    {
        EventCenter.GetInstance().EventTrigger("HideChessUI");
        currentSpotlightLattice = newLattice;
        
        // 使用 DOTween 移动物体到目标位置
        transform.DOMove(currentSpotlightLattice.transform.position, duration).onComplete = () =>
        {
            EventCenter.GetInstance().EventTrigger<Lattice>("ShowChessUI", currentSpotlightLattice);
        };

        // 使用 DOTween 改变虚拟相机的 OrthographicSize
        DOTween.To(() => virtualCamera.m_Lens.OrthographicSize, 
            x => virtualCamera.m_Lens.OrthographicSize = x, 
            3.0f, 
            duration);
        
    }
    
}
